﻿
/* 
 * Since 2008 - 2012
 */
package com.hh.bss.sysadmin.controller;

import static com.hh.bss.util.extjs.JsonHelper.outJson;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.filters.MappingPropertyFilter;
import net.sf.json.util.PropertyFilter;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;


import com.hh.bss.base.*;
import com.hh.bss.common.cache.SystemDicCache;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.sysadmin.dao.*;
import com.hh.bss.sysadmin.entity.*;
import com.hh.bss.sysadmin.service.*;
import com.hh.bss.sysadmin.vo.query.*;
import com.hh.bss.util.*;
import com.hh.bss.util.extjs.ExtJsPageHelper;
import com.hh.bss.util.extjs.JsonHelper;
import com.hh.bss.util.extjs.ListRange;

import java.util.*;





@Controller
public class SystemDicController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	private SystemDicService systemDicService;
	
	private SystemDic systemDic;
	java.lang.Integer id = null;
	private String[] items;

	
	
	/** 通过spring自动注入 */
	public void setSystemDicServiceImpl(SystemDicService service) {
		this.systemDicService = service;
	}	
	
	
	
	public void setId(java.lang.Integer val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}



	/**
	 * ExtGrid使用
	 * 列表
	 * @throws IOException
	 */
	public void list(HttpServletRequest request,HttpServletResponse response,SystemDicQuery systemDicQuery) throws IOException
	{
		PageRequest<Map> pr = ExtJsPageHelper.createPageRequestForExtJs(request, DEFAULT_SORT_COLUMNS);
		Page page = systemDicService.findPage(systemDicQuery);
		
		List<SystemDic> SystemDiclist = (List) page.getResult();
		ListRange<SystemDic> resultList = new ListRange<SystemDic>();
		resultList.setRows(SystemDiclist);
		resultList.setTotal(page.getTotalCount());
		resultList.setMessage("ok");
		resultList.setSuccess(true);
		outJson(response,resultList);
	}
	 public String managerPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
			
			//return "forward:/jsp/sysadmin/systemDic/systemDicPage.jsp";
		 return "forward:/jsp/systemDicManagerPage.jsp";
			
 }

	/**
	 * extGrid保存
	 * @throws IOException
	 */
	public void save(HttpServletRequest request,HttpServletResponse response,SystemDic systemDic) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
                        //设置创建用户和创建时间
			com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(SystemDic.class,"creator")) {
						try{com.hh.bss.util.BeanUtils.setProperty(systemDic,"creator",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemDic.class,"createDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(systemDic,"createDt",new Date());}catch(Exception ex){}
				}

			systemDicService.save(systemDic);
			result.put("success", true);
			result.put("msg", "添加成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		//刷新缓存
		SystemDicCache.refresh();
		outJson(response,result);
	}
	
	/**
	 * extGrid修改
	 * @throws IOException
	 */
	public void update(HttpServletRequest request,HttpServletResponse response,SystemDic systemDic) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
                        SystemDic oldsystemDic = (SystemDic)systemDicService.getById(systemDic.getId());
                         
			bind(request,oldsystemDic);
                        //设置修改用户和修改时间 
                        com.hh.bss.auth.client.OnlineManager onlineManager=super.getOnlineManager(request, response);
			if (onlineManager!=null){
					com.hh.bss.auth.client.OnlineUser onlineUser=onlineManager.getOnlineUser();
					if (onlineUser!=null&&com.hh.bss.util.BeanUtils.isExistsProperty(SystemDic.class,"modifier")) {
						try{com.hh.bss.util.BeanUtils.setProperty(oldsystemDic,"modifier",onlineUser.getUsername());}catch(Exception ex){}
					}
				}
							
			if (com.hh.bss.util.BeanUtils.isExistsProperty(SystemDic.class,"modifiedDt")) {
					try{com.hh.bss.util.BeanUtils.setProperty(oldsystemDic,"modifiedDt",new Date());}catch(Exception ex){}
				}


			systemDicService.update(oldsystemDic);
			result.put("success", true);
			result.put("msg", "修改成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		//刷新缓存
		SystemDicCache.refresh();
		outJson(response,result);
	}
	public void getParentId(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String id = request.getParameter("id");
		
		SystemDic oldsystemDic = (SystemDic)systemDicService.getById(StringHelper.parseInteger(id, 0));
		
		
	}
	public void getParent(HttpServletRequest request,HttpServletResponse response,SystemDic systemDic) throws IOException
	{
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			
                         
			SystemDic oldsystemDic = (SystemDic)systemDicService.getById(systemDic.getId());
			SystemDic psystemDic=null;
			if (oldsystemDic.getParentId().intValue()==0)
				{
					 psystemDic=new SystemDic();
					 psystemDic.setId(0);
					 psystemDic.setCodeNameCn("无");
					
				}	
			else  psystemDic = (SystemDic)systemDicService.getById(oldsystemDic.getParentId());

			if(psystemDic!=null) result.put("data", psystemDic);
			
			result.put("data", psystemDic);
			result.put("success", true);
			result.put("msg", "成功!");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		outJson(response,result);
	}
	/**
	 * extGrid删除
	 * @throws IOException
	 */
	public void delete(HttpServletRequest request,HttpServletResponse response) throws IOException
	{
		String ids = request.getParameter("ids");
		String[] idarray = ids.split(",");
		Map<String, Object> result = new HashMap<String, Object>();
		try
		{
			for (int i = 0; i < idarray.length; i++)
			{
				java.lang.Integer id = new java.lang.Integer((String)idarray[i]);
				systemDicService.removeById(id);
			}
			result.put("success", true);
			result.put("msg", "删除成功");
		}
		catch (Exception e)
		{
			result.put("failure", true);
			result.put("msg", e.getMessage());
			e.printStackTrace();
		}
		//刷新缓存
		SystemDicCache.refresh();
		outJson(response,result);
	}
	public void listconstdic(HttpServletRequest request,HttpServletResponse response,SystemDicQuery systemDicQuery) throws IOException
	{
		
	}
	public void listdic(HttpServletRequest request,HttpServletResponse response,SystemDicQuery systemDicQuery) throws IOException
	{
		try{
		
		Object categorys=null;
		boolean isVar=false;
		if (!StringHelper.isEmpty(request.getParameter("isvar"))){
			 isVar=true;
		}
		
		if (StringHelper.isEmpty(systemDicQuery.getCategory())){
			
		   categorys=SystemDicCache.getSystemDicCategoryListMap();
		}
		else {
			categorys=SystemDicCache.getCategoryList(systemDicQuery.getCategory(),request.getParameter("q"));
			
		}
		
		JsonConfig jsonConfig = new JsonConfig();    
		Map mf=new HashMap();
		   mf.put(SystemDic.class, new PropertyFilter() {
			    public boolean apply(Object source, String name, Object value) {
			    //name--map里key的字符，或是bean里的属性
			    //map里的value,或是bean里的属性的值
			    //如果上层的数据给拦截了，那底层的数据将不能被转换
			    //source 可能是hash或bean等	
			     Set set=new HashSet();
			     set.add("id");
			     set.add("codeNbr");
			     set.add("codeNameCn");			     
			     set.add("codeNameEn");
			     set.add("parentId");
			     //set.add("category");
			     if (SystemDic.class.equals(source.getClass())&&! set.contains(name)){
			    	 return true;
			     }	 
			     return false;
			    }
			   });
		   jsonConfig.setJsonPropertyFilter(new MappingPropertyFilter(mf) {
			   protected boolean keyMatches( Object key, Object source, String name, Object value ) {			   
				     return true;
				   } 
				   });  
        
		//System.out.println(JSONObject.fromObject(m,jsonConfig).toString());
		StringBuffer sb=new StringBuffer();

		String jsonStr="";
		
		if (isVar)
		   jsonStr=JSONObject.fromObject(categorys,jsonConfig).toString();
		else jsonStr=JSONArray.fromObject(categorys,jsonConfig).toString();

		if (isVar)sb.append("var allDic=").append(jsonStr).append(";");
		else sb.append(jsonStr);
		JsonHelper.outJsonString(response,sb.toString());
		//systemDicCache.setSystemDicDaoImpl(systemDicService.g);
		}catch(Exception ex){
			ex.printStackTrace();
			//throw ex;
		}
	}

	
}
